import { login, getInfo } from "api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
// import router from '@/router'
const LOGIN = "LOGIN"; // 获取用户信息
const SetUserData = "SetUserData"; // 获取用户信息
const LOGOUT = "LOGOUT"; // 退出登录、清除用户数据
const USER_DATA = "userDate"; // 用户数据
const getID = "getID";
export default {
  namespaced: true,
  state: {
    token: getToken() || null,
    user: JSON.parse(localStorage.getItem(USER_DATA) || null),
    userID: "",
  },
  mutations: {
    [LOGIN](state, data) {
      let userToken = data.token;
      state.token = userToken;
      setToken(userToken);
    },
    [SetUserData](state, userData = {}) {
      state.user = userData;
      localStorage.setItem(USER_DATA, JSON.stringify(userData));
    },
    [LOGOUT](state) {
      state.user = null;
      state.token = null;
      removeToken();
      localStorage.removeItem(USER_DATA);
      resetRouter();
    },
    [getID](state, id) {
      state.userID = id;
    },
  },
  actions: {
    async login(state, data) {
      try {
        // let res = await login({
        //   username: data.phoneNumber,
        //   password: data.password
        // });
        // localStorage.setItem("accessToken", res.token);
        // localStorage.setItem("user", res.id);
        // state.commit(getID, res.id);
        // state.commit(LOGIN, res);

        state.commit(LOGIN, { token: data.tok });

        setTimeout(() => {
          const redirect = data.$route.query.redirect || "/home";
          console.log(redirect);
          data.$router.replace({
            path: redirect,
          });
          // data.$router.push("/home");
          // console.log("跳转成功");
        }, 100);
      } catch (error) { console.log("失败"); } finally {
        console.log("finallys");

      }
    },
    // get user info
    getInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token)
          .then(response => {
            const { data } = response;

            if (!data) {
              // eslint-disable-next-line
              reject("Verification failed, please Login again.");
            }
            commit(SetUserData, data);
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
  },
  getters: {
    token(state) {
      return state.token;
    },
    user(state) {
      return state.user;
    },
  },
};
